/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 修改所属支局、审核通过弹窗
 */
import React, { useState, useEffect, useCallback } from "react";
import { connect } from "dva";
import { Form, Modal, Select, Row, Col, Input } from "antd";
import AddressCascader from "@/components/AddressCascader";

const { Option } = Select;
const FormItem = Form.Item;

const ModifyZYModal = Form.create()(
  React.memo(props => {
    const { visible, showModal, record = {}, form, dispatch, user, getList, ...restProps } = props;
    const { validateFields, getFieldDecorator, setFieldsValue, isFieldsTouched } = form;
    const {
      currentUser: { user_info },
    } = user;
    const {
      province,
      city,
      district,
      concat_location,
      branch,
      phone,
      create_at,
      path,
      cm_id,
      // 驿站详细信息
      relation,
      source,
      workplace_info,
      business_pattern,
      zone,
      workplace_type,
      mechanism_no,
    } = record;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };

    const [placeholder, setPlaceholder] = useState("");
    const [initBranch, setBranch] = useState([]);
    const [showOrganizeCode, setShowOrganizeCode] = useState(!!mechanism_no);

    useEffect(
      () => {
        if (mechanism_no) {
          setShowOrganizeCode(true);
        } else {
          setShowOrganizeCode(false);
        }
      },
      [mechanism_no]
    );

    useEffect(
      () => {
        if (branch && visible) {
          const sortBranchId = branch.filter(val => val.level > 0).map(i => i.id);
          setFieldsValue({
            branch_id: sortBranchId,
          });
          setBranch(branch);
        }
        if (path == "under_modify") {
          setPlaceholder("请选择所属支局");
        } else {
          setPlaceholder("请为该驿站选择一个所属的支局");
        }
      },
      [cm_id, visible, path, branch, setFieldsValue]
    );

    const onOk = useCallback(
      () => {
        const isFormChanged = isFieldsTouched();
        if (!isFormChanged) {
          showModal(false);
          return;
        }
        validateFields((err, value) => {
          if (err) return;
          let type;
          const formVlaus = { ...value };
          formVlaus.cm_id = cm_id;
          formVlaus.to_branch_id = [...formVlaus.branch_id].reverse()[0]; // 解构防止需改原数据
          delete formVlaus.branch_id;
          if (path == "under_modify") {
            type = "area/zyChangeBranch";
          } else if (path == "postDetail") {
            type = "area/zyAudit";
            formVlaus.status = 1;
          } else {
            type = "area/zyAudit";
            formVlaus.status = 1;
          }
          dispatch({
            type,
            payload: {
              ...formVlaus,
            },
          }).then(() => {
            showModal && showModal(false);
            getList && getList();
          });
        });
      },
      [path, cm_id, dispatch, getList, showModal, validateFields, isFieldsTouched]
    );

    const onCancel = () => {
      showModal && showModal(false);
    };
    const selectStyle = {
      marginBottom: 0,
    };

    const onBusinessPatternChange = useCallback(val => {
      setShowOrganizeCode(val == "邮乐购站点叠加");
    }, []);

    return (
      <Modal
        destroyOnClose
        width={700}
        title="审核"
        visible={visible}
        onOk={onOk}
        onCancel={onCancel}
        {...restProps}
      >
        <Form layout="horizontal">
          {path != "postDetail" && (
            <Row>
              <Col span={6}>
                <span>账号:</span>
                <span>{phone}</span>
              </Col>
              <Col span={10}>
                <span>地址:</span>
                <span>{province + city + district + concat_location}</span>
              </Col>
            </Row>
          )}
          <FormItem label="选择支局名称" {...formItemLayout}>
            {getFieldDecorator("branch_id", {
              initialValue: [],
              rules: [
                {
                  required: true,
                },
                {
                  validator: (rule, value, callback) => {
                    if (value.length < 4) {
                      callback(rule.message);
                      return;
                    }
                    callback();
                  },
                  message: "请选择所属支局",
                },
              ],
            })(
              <AddressCascader
                request
                type={path} // under_modify(下属驿站，修改所属支局), audit(待审核驿站，审核通过)，postDetail（下属驿站，修改驿站经营信息）
                branch={initBranch}
                placeholder={placeholder}
                companyId={user_info && user_info.branchId}
              />
            )}
          </FormItem>
          {// 下属驿站不显示
          path !== "under_modify" && (
            <>
              <FormItem label="经营者与邮政关系:" {...formItemLayout}>
                {getFieldDecorator("relation", {
                  initialValue: relation,
                  rules: [{ required: true, message: "请选择经营者与邮政关系!" }],
                })(
                  <Select style={selectStyle} placeholder="请选择经营者与邮政关系">
                    <Option value="邮政自营">邮政自营-邮政员工兼职运营</Option>
                    <Option value="众创众亨">众创众亨-邮政提供场所，员工专职运营</Option>
                    <Option value="创业计划">创业计划-邮政提供场所，社会资本运营</Option>
                    <Option value="自主经营">自主经营-场所与人员均为社会资本</Option>
                  </Select>
                )}
              </FormItem>
              <FormItem label="驿站来源" {...formItemLayout}>
                {getFieldDecorator("source", {
                  initialValue: source,
                  rules: [{ required: true, message: "请选择驿站来源!" }],
                })(
                  <Select style={selectStyle} placeholder="请选择驿站来源">
                    <Option value="新建驿站">新建驿站</Option>
                    <Option value="易邮自提转型">易邮自提转型</Option>
                    <Option value="快宝转型">快宝转型</Option>
                    <Option value="其他驿站转型">其他驿站转型</Option>
                  </Select>
                )}
              </FormItem>
              <FormItem label="驿站场所信息" {...formItemLayout}>
                {getFieldDecorator("workplace_info", {
                  initialValue: workplace_info,
                  rules: [{ required: true, message: "请选择驿站场所信息!" }],
                })(
                  <Select style={selectStyle} placeholder="请选择驿站场所信息">
                    <Option value="自有局房">自有局房-驿站场所属邮政所有（租用除外）</Option>
                    <Option value="配套用房">配套用房-由政府或驻点单位等免费提供的各类房产</Option>
                    <Option value="邮政租用">邮政租用-邮政租用社会房产</Option>
                    <Option value="经营者自有（租用）">
                      经营者自有（租用）-邮政不出资，场地也非邮政所有
                    </Option>
                  </Select>
                )}
              </FormItem>
              <FormItem label="驿站经营方式" {...formItemLayout}>
                {getFieldDecorator("business_pattern", {
                  initialValue: business_pattern,
                  rules: [{ required: true, message: "请选择驿站经营方式!" }],
                })(
                  <Select
                    style={selectStyle}
                    placeholder="请选择驿站经营方式"
                    onChange={onBusinessPatternChange}
                  >
                    <Option value="邮政综合网点叠加">邮政综合网点叠加</Option>
                    <Option value="邮政普服网点叠加">邮政普服网点叠加</Option>
                    <Option value="邮政寄递揽投站点叠加">邮政寄递揽投站点叠加</Option>
                    <Option value="邮政金融网点叠加">邮政金融网点叠加</Option>
                    <Option value="邮乐购站点叠加">邮乐购站点叠加</Option>
                    <Option value="超市（便利店）叠加">超市（便利店）叠加</Option>
                    <Option value="单独经营">单独经营</Option>
                    <Option value="其它">其它</Option>
                  </Select>
                )}
              </FormItem>
              {showOrganizeCode && (
                <FormItem label="掌柜机构号" {...formItemLayout}>
                  {getFieldDecorator("mechanism_no", {
                    initialValue: mechanism_no,
                    rules: [{ required: true, message: "请输入邮乐购站点的掌柜机构号!" }],
                  })(<Input placeholder="请输入掌柜机构号" />)}
                </FormItem>
              )}
              <FormItem label="驿站所属区位" {...formItemLayout}>
                {getFieldDecorator("zone", {
                  initialValue: zone,
                  rules: [{ required: true, message: "请选择驿站所属区位!" }],
                })(
                  <Select style={selectStyle} placeholder="请选择驿站所属区位">
                    <Option value="城区">城区-县城以上城区特快专业揽投部揽收范围内</Option>
                    <Option value="城郊结合部">
                      城郊结合部-县城以上城区特快专业揽投部揽收范围内
                    </Option>
                    <Option value="乡镇">乡镇</Option>
                    <Option value="行政村（自然村）">行政村（自然村）</Option>
                  </Select>
                )}
              </FormItem>
              <FormItem label="驿站所在场所" style={selectStyle} {...formItemLayout}>
                {getFieldDecorator("workplace_type", {
                  initialValue: workplace_type,
                  rules: [{ required: true, message: "请选择驿站所在场所!" }],
                })(
                  <Select placeholder="请选择驿站所在场所">
                    <Option value="校园">校园</Option>
                    <Option value="商圈">商圈-商厦、集群市场</Option>
                    <Option value="写字楼">写字楼</Option>
                    <Option value="园区">园区</Option>
                    <Option value="社区（乡镇、村）">社区（乡镇、村）</Option>
                  </Select>
                )}
              </FormItem>
            </>
          )}
        </Form>
      </Modal>
    );
  })
);
export default connect(({ user }) => ({ user }))(ModifyZYModal);
